/* Papastefanos Serafeim */
/* Ulopoihsh sunarthsewn ouras */

#include "que.h"

/* Pros9etei to mhnuma buf sto telos ths oura */
void enque(char *buf, Queue *q) {
	Node *nod;
	nod=(Node *)malloc(sizeof(Node));
	if(nod == NULL) {
		perror("malloc");
		exit(-1);
	}
	nod->data=buf;
	nod->next=NULL;

	q->size++;

	if(q->first==NULL) {
		q->first=nod;
		q->last=nod;
	} else {
		q->last->next=nod;
		q->last=nod;
	}
}

/* Emfanizei ta periexomena ths ouras */
void viewQueue(Queue *q) {
	Node *p;
	p=q->first;
	if(p==NULL) {
		printf("Adeia oura.");
		return; 
	} else {
		printf("\nMege9os ouras = %d. ", q->size);
		while(p->next!=NULL) {
			printf(" %s ",p->data);
			p=p->next;
		}
		printf(" %s ",p->data);
	}
}

/* Epistrefei to epomeno mhnuma apo thn arxh ths ouras */
char *deque(Queue *q) {
	if(q->first == NULL) { 
		printf("Adeia oura.");
		return NULL;
	}
	Node *p;
	char *c=q->first->data;
	p=q->first;
	q->first=q->first->next;
	if(q->first == NULL) q->last = NULL;
	free(p);
	q->size--;
	return c;
}

/* Dhmiourgei mia nea, adeia oura */
Queue *createQueue(void) {
	Queue *tmp = (Queue *)malloc(sizeof(Queue) );
	if(tmp == NULL) return NULL;
	tmp->first = NULL;
	tmp->last = NULL;
	tmp->size = 0;
	return tmp;
}

/* Elegxei an h oura einai adeia */
int isEmpty(Queue *q) {
	return (q->first == NULL);	
}

/* Eleu9erwnei th mnhmh pou katalamvanei h oura */
void freeQueue(Queue *q) {
	Node *p = q->first;
	while(p->next != NULL) {
		Node *r = p;
		p=p->next;
		free(r);
	}
	free(q);
}
